package com.flyduck.modules.app.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.entity.AppOrder;
import com.flyduck.entity.AppOrderItem;
import com.flyduck.entity.AppRefund;
import com.flyduck.mapper.AppOrderItemMapper;
import com.flyduck.mapper.AppOrderMapper;
import com.flyduck.mapper.AppRefundMapper;
import com.flyduck.modules.app.constant.AppConstant;
import com.flyduck.manager.AppOrderManager;
import com.flyduck.manager.AppRefundManager;
import com.flyduck.manager.AppUploadManager;
import com.flyduck.utils.TokenUtils;
import com.flyduck.modules.app.service.AppRefundService;
import com.flyduck.modules.app.vo.refund.AppRefundApplyReqVO;
import com.flyduck.modules.app.vo.refund.AppRefundBaseDataRespVO;
import com.flyduck.utils.BeanUtils;
import com.flyduck.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * AppRefundServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-05-23
 */
@Service
public class AppRefundServiceImpl implements AppRefundService {

    @Resource
    private AppOrderManager appOrderManager;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private AppOrderItemMapper appOrderItemMapper;
    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private AppRefundManager appRefundManager;
    @Resource
    private AppRefundMapper appRefundMapper;
    @Resource
    private AppUploadManager appUploadManager;

    @Override
    public AppRefundBaseDataRespVO getRefundBaseDataByOrderId(Long orderId) {
        AppOrder appOrder = appOrderManager.verifyAppOrderById(orderId);
        AppRefundBaseDataRespVO.AppOrderDTO appOrderDTO = BeanUtils.toBean(appOrder, AppRefundBaseDataRespVO.AppOrderDTO.class);

        List<AppOrderItem> appOrderItemList = appOrderItemMapper.getAppOrderItemListByOrderId(orderId);
        List<AppRefundBaseDataRespVO.AppOrderItemDTO> appOrderItemDTOS = BeanUtils.toBeanList(appOrderItemList, AppRefundBaseDataRespVO.AppOrderItemDTO.class);
        appOrderDTO.setOrderItems(appOrderItemDTOS);

        AppRefundBaseDataRespVO appRefundBaseDataRespVO = new AppRefundBaseDataRespVO();
        appRefundBaseDataRespVO.setOrder(appOrderDTO);
        appRefundBaseDataRespVO.setReasons(
                Arrays.asList(
                        "多拍/拍错/不想要了",
                        "不喜欢/效果不好",
                        "少件/发错货/未收到货",
                        "商品与描述不符",
                        "商品质量/故障"
                )
        );
        appRefundBaseDataRespVO.setMethods(
                Arrays.asList(
                        "自行寄回",
                        "上门取货",
                        "仅退款"
                )
        );
        return appRefundBaseDataRespVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refundApply(AppRefundApplyReqVO appRefundApplyReqVO, MultipartFile[] pics) {
        Long userId = tokenUtils.getCurrentUserId();
        AppRefund appRefund = BeanUtils.toBean(appRefundApplyReqVO, AppRefund.class);
        //1、判断是否可以申请退货
        AppOrder appOrder = appOrderManager.verifyAppOrderById(appRefund.getOrderId());
        //待发货、待收货、已完成才符合
        if(!Arrays.asList(
                AppConstant.OrderStatus.PENDING_DELIVERY.getCode(),
                AppConstant.OrderStatus.PENDING_RECEIPT.getCode(),
                AppConstant.OrderStatus.COMPLETED.getCode()
        ).contains(appOrder.getOrderStatus())){
            throw new BusinessException("该订单不支持退款");
        }

        //2、根据订单状态区分处理
        //待发货：立即退款
        //待收货、已完成：进入后台处理
        if(AppConstant.OrderStatus.PENDING_DELIVERY.getCode() == appOrder.getOrderStatus()){
            appOrder.setOrderStatus(AppConstant.OrderStatus.REFUNDED.getCode());
            appRefund.setRefundStatus(AppConstant.ReturnStatus.COMPLETED.getCode());

            //TODO 支付宝退款处理
        }else {
            appOrder.setOrderStatus(AppConstant.OrderStatus.REFUND_REQUESTED.getCode());
            appRefund.setRefundStatus(AppConstant.ReturnStatus.PENDING_PROCESSING.getCode());
        }

        //3、图片处理
        if(ArrayUtil.isNotEmpty(pics)){
            try {
                List<String> picUrls = appUploadManager.upload(pics, 0.5f, 0.2);
                appRefund.setImages(StringUtils.join(";", picUrls));
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            }
        }


        //4、更新状态
        appRefund.setOrderSn(appOrder.getSn());
        appRefund.setUserId(userId);
        appRefund.setSn(appRefundManager.generateRefundSn());
        appRefund.setRefundAmount(appOrder.getTotalAmount());
        appRefund.setCreated(LocalDateTime.now());
        appRefundMapper.insert(appRefund);

        appOrderMapper.updateById(appOrder);

    }
}
